import { ref, reactive, computed } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { listAddress, getAddress, addAddress, updateAddress, delAddress } from '@/api/address/address';
import { getUserProfile } from '@/api/system/user';

/**
 * 地址信息接口
 */
export interface AddressInfo {
    id: string;          // 地址ID
    name: string;        // 收货人姓名
    phone: string;       // 手机号码
    region: string;      // 地区
    address: string;     // 详细地址
    tag: string;         // 地址标签
    isDefault: boolean;  // 是否为默认地址
}

// 共享的地址数据
const addressStore = {
    list: ref<AddressInfo[]>([]),
    tags: ref(['家', '公司', '学校']),
    userId: ref<number | null>(null)
};

/**
 * 格式化手机号，中间4位用星号代替
 */
export function formatPhoneNumber(phone: string): string {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

// 提取共享的刷新地址列表函数
async function refreshAddressList() {
    try {
        const response = await listAddress({});
        if (response.code === 200) {
            addressStore.list.value = response.rows.map(item => ({
                id: item.id,
                name: item.consignee,
                phone: item.contactPhone,
                region: item.address.split(' ')[0] || '',
                address: item.address.split(' ').slice(1).join(' ') || item.address,
                tag: item.addressType || '家',
                isDefault: item.defaultFlag === 1 || item.defaultFlag === '1'
            }));
        } else {
            uni.showToast({
                title: '获取地址列表失败',
                icon: 'none'
            });
        }
    } catch (error) {
        uni.showToast({
            title: '获取地址列表失败',
            icon: 'none'
        });
    }
}

/**
 * 地址列表页面Hook
 */
export function useAddressListPage() {
    const addressList = addressStore.list;
    const userId = addressStore.userId;
    const emptyStatus = computed(() => addressList.value.length === 0);

    // 获取用户信息
    async function getUserInfo() {
        try {
            const res = await getUserProfile();
            userId.value = Number(res.data.userId);
            await refreshAddressList();
        } catch (error) {
            console.error('获取用户信息失败:', error);
            uni.showToast({
                title: '获取用户信息失败',
                icon: 'none'
            });
        }
    }

    // 页面加载时获取用户信息
    onLoad(() => {
        getUserInfo();
    });

    // 设置默认地址
    async function setDefaultAddress(id: string): Promise<boolean> {
        try {
            const address = addressList.value.find(item => item.id === id);
            if (!address) return false;

            // 构建完整的地址字符串
            const fullAddress = address.region && address.address
                ? `${address.region} ${address.address}`
                : address.address || address.region;

            // 先将所有地址设置为非默认
            const otherAddresses = addressList.value.filter(item => item.id !== id);
            for (const otherAddress of otherAddresses) {
                if (otherAddress.isDefault) {
                    const otherFullAddress = otherAddress.region && otherAddress.address
                        ? `${otherAddress.region} ${otherAddress.address}`
                        : otherAddress.address || otherAddress.region;

                    await updateAddress({
                        id: otherAddress.id,
                        userId: userId.value,
                        consignee: otherAddress.name,
                        contactPhone: otherAddress.phone,
                        address: otherFullAddress,
                        addressType: otherAddress.tag,
                        defaultFlag: 0
                    });
                }
            }

            // 设置当前地址为默认
            const response = await updateAddress({
                id: id,
                userId: userId.value,
                consignee: address.name,
                contactPhone: address.phone,
                address: fullAddress,
                addressType: address.tag,
                defaultFlag: 1
            });

            if (response.code === 200) {
                await refreshAddressList();
                return true;
            }
            return false;
        } catch (error) {
            return false;
        }
    }

    // 删除地址
    async function deleteAddress(id: string): Promise<boolean> {
        try {
            const response = await delAddress(id);
            if (response.code === 200) {
                // 更新本地数据
                addressList.value = addressList.value.filter(item => item.id !== id);
                return true;
            }
            return false;
        } catch (error) {
            console.error('删除地址失败:', error);
            return false;
        }
    }

    // 页面显示时刷新数据
    onShow(() => {
        if (userId.value) {
            refreshAddressList();
        }
    });

    return {
        addressList,
        emptyStatus,
        setDefaultAddress,
        deleteAddress,
        refreshAddressList // 导出刷新函数
    };
}

/**
 * 地址编辑页面Hook
 */
export function useAddressEditPage() {
    const addressList = addressStore.list;
    const addressTags = addressStore.tags;
    const userId = addressStore.userId;

    const isEdit = ref(false);
    const editId = ref('');
    const defaultAddress = ref(false);
    const selectedTag = ref('家');

    const form = reactive({
        name: '',
        phone: '',
        region: '',
        address: ''
    });

    // 获取用户信息（如果还没有获取）
    async function ensureUserInfo() {
        if (!userId.value) {
            try {
                const res = await getUserProfile();
                userId.value = Number(res.data.userId);
            } catch (error) {
                console.error('获取用户信息失败:', error);
                throw error;
            }
        }
    }

    // 加载编辑数据
    async function loadAddressData(id: string): Promise<boolean> {
        try {
            const response = await getAddress(id);
            if (response.code === 200) {
                const address = response.data;
                form.name = address.consignee || '';
                form.phone = address.contactPhone || '';

                // 更好的地址分割逻辑
                if (address.address) {
                    const addressParts = address.address.split(' ');
                    if (addressParts.length > 1) {
                        form.region = addressParts[0];
                        form.address = addressParts.slice(1).join(' ');
                    } else {
                        // 如果没有空格分隔，尝试其他方式或全部作为详细地址
                        form.region = '';
                        form.address = address.address;
                    }
                } else {
                    form.region = '';
                    form.address = '';
                }

                selectedTag.value = address.addressType || '家';
                defaultAddress.value = address.defaultFlag === 1 || address.defaultFlag === '1';  // 兼容数字和字符串
                return true;
            }
            return false;
        } catch (error) {
            console.error('获取地址详情失败:', error);
            return false;
        }
    }

    // 初始化页面
    async function initEditPage(id?: string) {
        isEdit.value = !!id;
        editId.value = id || '';
        defaultAddress.value = false;
        selectedTag.value = '家';

        // 重置表单
        form.name = '';
        form.phone = '';
        form.region = '';
        form.address = '';

        // 确保有用户信息
        await ensureUserInfo();

        if (id) {
            const success = await loadAddressData(id);
            if (!success) {
                uni.showToast({
                    title: '加载地址信息失败',
                    icon: 'none'
                });
            }
        }
    }

    // 保存地址
    async function saveAddress(): Promise<boolean> {
        try {
            // 确保有用户信息
            await ensureUserInfo();

            // 构建完整的地址字符串
            const fullAddress = form.region && form.address
                ? `${form.region} ${form.address}`
                : form.address || form.region;

            const addressData = {
                userId: userId.value,
                consignee: form.name,
                contactPhone: form.phone,
                address: fullAddress,
                addressType: selectedTag.value,
                defaultFlag: defaultAddress.value ? 1 : 0
            };

            let response;
            if (isEdit.value) {
                response = await updateAddress({
                    id: editId.value,
                    ...addressData
                });
            } else {
                response = await addAddress(addressData);
            }

            if (response.code === 200) {
                // 如果设置为默认地址，需要取消其他默认地址
                if (defaultAddress.value) {
                    const listResponse = await listAddress({});
                    if (listResponse.code === 200) {
                        const otherAddresses = listResponse.rows.filter(item =>
                            item.id !== editId.value && item.defaultFlag === 1
                        );

                        for (const otherAddress of otherAddresses) {
                            await updateAddress({
                                ...otherAddress,
                                defaultFlag: 0
                            });
                        }
                    }
                }

                // 使用共享的刷新函数
                await refreshAddressList();
                return true;
            }
            return false;
        } catch (error) {
            return false;
        }
    }

    // 删除地址
    async function deleteAddress(): Promise<boolean> {
        if (!isEdit.value) return false;

        try {
            const response = await delAddress(editId.value);
            if (response.code === 200) {
                // 更新本地数据
                addressList.value = addressList.value.filter(item => item.id !== editId.value);
                return true;
            }
            return false;
        } catch (error) {
            console.error('删除地址失败:', error);
            return false;
        }
    }

    return {
        isEdit,
        editId,
        form,
        defaultAddress,
        selectedTag,
        addressTags,
        initEditPage,
        saveAddress,
        deleteAddress
    };
}
